package maven.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import lombok.Data;
import maven.TreeNode;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Author 史祥连
 * @Date 2024/2/2 11:39
 * @Version 1.0
 */

@Data
public class ExcelWriterHelper {

    /**
     * excel文件全路径（包含名称）
     */
    private String filePath;

    private ExcelWriter excelWriter ;

    public ExcelWriterHelper(String filePath) {
        this.filePath = filePath;
    }

    public void loadEasyExcelWrite() {
        this.excelWriter = EasyExcel.write(filePath, RefExcelDto.class).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
    }

    public void print(TreeNode curTreeNode, String prefix, Map<Long, TreeNode> treeNodeMap, List<String> printList, Map<String, String> result, WriteSheet writeSheet) {
        String pr = curTreeNode.getGroup() + ":" + curTreeNode.getJarName();
        printList.add(prefix + pr);

        Long parentId = curTreeNode.getParentId();
        if (parentId != null) {
            TreeNode treeNode = treeNodeMap.get(parentId);
            print(treeNode, prefix, treeNodeMap, printList, result, writeSheet);
        } else {
            StringBuilder sb2 = new StringBuilder();
            for (int i = printList.size() - 1; i >= 0; i--) {
                StringBuilder sb = new StringBuilder();
                for (int i1 = (printList.size() - i - 1); i1 > 0; i1--) {
                    sb.append("   ");
                }
                String all = sb + printList.get(i);
                sb2.append(all).append("\n");
                System.out.println(all);
            }
            RefExcelDto refExcelDto = new RefExcelDto(curTreeNode.getJarName(), curTreeNode.getVersion(), sb2.toString(),curTreeNode.getProjectName());
            excelWriter.write(Arrays.asList(refExcelDto),writeSheet);
            result.put(curTreeNode.getGroupJarName(), sb2.toString());
        }

    }

    /**
     * 读取excel文件
     * @param filePath
     * @return
     * @throws IOException
     * @author  史祥连
     * @date    2024/2/2-16:27
     * @version 1.0     */
    private static Workbook openExistingWorkbook(String filePath) throws IOException {
        try (FileInputStream fileInputStream = new FileInputStream(filePath)) {
            return WorkbookFactory.create(fileInputStream);
        }
    }

    public void appendLinkInfo(List<TreeNode> list) {

        Workbook appendWorkbook = getAppendWorkbook();
        Sheet infoSheet = appendWorkbook.createSheet("jar包信息");
        Row titleRow = infoSheet.createRow(0);
        // 创建一个样式对象
        CellStyle style = appendWorkbook.createCellStyle();
        // 设置背景色为蓝色
        style.setFillForegroundColor((short) 14);
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        setTitle(Arrays.asList("jar名称(点击跳转引用信息)","jar大小(MB)"), titleRow, style);

        for (int i = 1; i <= list.size(); i++) {
            Row row = infoSheet.createRow(i);
            Cell jarNameCell = row.createCell(0);
            CreationHelper createHelper = appendWorkbook.getCreationHelper();
            Hyperlink hyperlink = createHelper.createHyperlink(HyperlinkType.DOCUMENT);
            hyperlink.setAddress("'"+list.get(i-1).formatSheetName()+"'!A1");
            jarNameCell.setHyperlink(hyperlink);
            jarNameCell.setCellValue(list.get(i-1).getGroupJarName());
            Cell sizeCell = row.createCell(1);
            sizeCell.setCellValue(list.get(i-1).formatSize());
        }


        appendWorkbook.setSheetOrder("jar包信息",0);
        try (FileOutputStream fileOut = new FileOutputStream(filePath)) {
            appendWorkbook.write(fileOut);
            System.out.println("Excel 追加写入成功：" + filePath);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Excel 追加写入失败。");
        }

    }


    private static void setTitle(List<String> titles, Row titleRow, CellStyle style) {
        // 将样式应用到单元格
        for (int i = 0; i < titles.size(); i++) {
            Cell cell = titleRow.createCell(i);
            cell.setCellValue(titles.get(i));
            cell.setCellStyle(style);
        }
    }


    private Workbook getAppendWorkbook() {
        Workbook workbook = null;
        try {
            workbook = openExistingWorkbook(filePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return workbook;
    }

}
